<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class NoticeController extends BaseController
{

    /**
     * 获取通知
     * @return \Illuminate\Http\JsonResponse
     */
    public function getNotice()
    {
        $data=DB::table('notices_users')
            ->where('users_id',\request()->userId)
            ->leftJoin('notices','notices_users.notice_id','=','notices.id')
            ->orderBy('notices_users.is_read')
            ->orderBy('notices.created_at','desc')
            ->paginate(\request()->input('limit',10));

        foreach ($data as &$item){
            $item->created_at=date('Y-m-d H:i',$item->created_at);
        }

        return $this->success($data);
    }

    /**
     * 已讀通知
     * @return \Illuminate\Http\JsonResponse
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function readNotice()
    {
        if(!request()->get('id')) return $this->apiError('id不能為空');

       $res= DB::table('notices_users')->where('users_id',\request()->userId)
            ->where('notice_id',\request()->get('id'))->update(['is_read'=>1]);

       if($res) return $this->success('OK');

       return $this->apiError('失敗');
    }

    /**刪除通知
     * @return \Illuminate\Http\JsonResponse
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function deleteNotice()
    {
        if(!request()->get('id')) return $this->apiError('id不能為空');

        $res= DB::table('notices_users')->where('users_id',\request()->userId)
            ->where('notice_id',\request()->get('id'))->delete();
        if($res) return $this->success('OK');
        return $this->apiError('失敗');
    }
}
